package com.senven.common.back.filter;

import com.alibaba.fastjson.JSON;
import com.senven.common.back.entity.Anon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//*
// * @BelongsProject: senven-orderfood-parent
// * @BelongsPackage: com.senven.back.filter
// * @unthor : YSH
// * @date : 2022/8/30 19:29


@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private Anon anon;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("你好==============");
        //获取request和response对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();


        //获取请求的路径
        String path = request.getPath().toString();
        //判断是否为匿名访问路径
        if (anon.getUrl().contains(path)) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        System.out.println(token);
        System.out.println(path);
        //是否携带请求token以及token是否有效
        if (StringUtils.hasText(token) && redisTemplate.hasKey(token)) {
            System.out.println("dfdfd");
            //是否时登录直接放行的路径
            System.out.println(anon.getLogin());
            System.out.println(path);
            if (anon.getLogin().contains(path)) {
                System.out.println("进来了llll");
                return chain.filter(exchange);
            }
            System.out.println("出来了");
            //判断当前登录者是否具有相应的权限。
            ValueOperations<String, String> forValue = redisTemplate.opsForValue();
            String json = forValue.get(token);
            Map o = JSON.parseObject(json, Map.class);
            //获取map中的权限
            List<String> permissions = (List<String>) o.get("permissions");
            System.out.println("权限~~~~~~~~~~~~~~~~~~~");
            System.out.println(permissions);
            if(permissions.contains(path)){
                return chain.filter(exchange);
            }else{
                return result(response,"权限不足",4001);
            }

        }else{
            return result(response,"请先登录",4002);
        }
    }

    private Mono<Void> result(ServerHttpResponse response ,String msg,Integer code){
        //3.返回一个json数据。
        //3.1设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        //3.2封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("msg", msg);
        map.put("code", code);

        //3.3作JSON转换
        byte[] bytes = JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8);

        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
    }
